package org.vectrics.recruiter.user.resume.email;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.apache.log4j.Logger;

public class EmailExtractor {
	private transient Logger log = Logger.getLogger(this.getClass());
	public static final String REGULAR_EXPRESSION = "^((?:(?:(?:[a-zA-Z0-9][\\.\\-\\+_]?)*)[a-zA-Z0-9])+)\\@((?:(?:(?:[a-zA-Z0-9][\\.\\-_]?){0,62})[a-zA-Z0-9])+)\\.([a-zA-Z0-9]{2,6})$";

	
	public Set findEmailInText(WordList wordList) {
		log.debug("findEmailInText() - starting");
		Set emails = new HashSet();
		Word previousWord1 = null;
		Word previousWord2 = null;
		Word previousWord3 = null;
		Iterator iter = wordList.iterator();
		while (iter.hasNext()) {
			Word word = (Word)iter.next();
			if (log.isDebugEnabled())
				log.debug("findEmailInText() - looking at word: " + word);
			if (word.getType().equals(Word.TYPE_WORD)) {
				
				String value = word.getValue();
				if ((value.length() > 3) && (value.indexOf("@") > 0) && (value.indexOf("@") < 20) && (value.matches(this.REGULAR_EXPRESSION))) {
					emails.add(word.getValue());
					log.debug("findEmailInText() - word matches email format");
				} 
			} 
			previousWord3 = previousWord2;
			previousWord2 = previousWord1;
			previousWord1 = word;

			if ((previousWord3 != null) && (previousWord2 != null) && (previousWord1 != null)) {
				String value = previousWord3.getValue() + previousWord2.getValue() + previousWord1.getValue();
				if ((value.length() > 3) && (value.indexOf("@") > 0) && (value.indexOf("@") < 20) && (value.matches(this.REGULAR_EXPRESSION))) {
					emails.add(value);
				}
			}
			
		}
		log.debug("findEmailInText() - finished");
		return(emails);
	}
	
}
